# -*- coding:utf-8 -*-
"""
" ip2region python seacher client module
"
" Autho: koma<komazhang@foxmail.com>
" Date : 2015-11-06
"""
from __future__ import unicode_literals
import struct, sys, os, time
from platform import python_version

from ip2Region import Ip2Region

from flask import Flask
from flask import request
from flask import jsonify

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False


@app.route('/')
def hello_world():
    return 'access [心.top] for more message.\n access [./js] or [./json] to get different user data.'


@app.route("/json", methods=["GET"])
def ipjson():
    ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
    dict1 = testSearch(ip)
    dict2 = {'ip': ip}
    dnew = Merge(dict2, dict1)
    # to_str = str(dnew)
    print(dnew)
    return jsonify(dnew), 200


@app.route("/js", methods=["GET"])
def ipjs():
    ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
    dict1 = testSearch(ip)
    dict2 = {'ip': ip}
    dnew = Merge(dict2, dict1)
    # to_str = str(dnew)
    strrr = "var ip_data =" + str(dnew)
    return strrr, 200


def Merge(dict1, dict2):
    res = {**dict1, **dict2}
    return res


def testSearch(resvip):
    """
    " ip2region test function
    """
    argLen = len(sys.argv)
    version = python_version()
    algorithms = ["binary", "b-tree", "memory"]

    if argLen < 2:
        print("Usage: python testSearcher.py [ip2region db file] [alrogrithm]")
        print("Algorithm: %s" % ", ".join(algorithms))
        return 0

    dbFile = sys.argv[1]

    if (not os.path.isfile(dbFile)) or (not os.path.exists(dbFile)):
        print("[Error]: Specified db file is not exists.")
        return 0

    if argLen > 2:
        algorithm = sys.argv[2]
    try:
        algorithms.index(algorithm)
    except Exception as e:
        algorithm = "b-tree"

    print("initializing %s..." % (algorithm))
    print("+----------------------------------+")
    print("| ip2region test program           |")
    print("+----------------------------------+")

    searcher = Ip2Region(dbFile)

    while True:
        if version[:1] == "2":
            line = raw_input("ip2region>> ")
        else:
            print("ip2region>> ")
            line = resvip
        line = line.strip()

        if line == "":
            print("[Error]: Invalid ip address.")
            continue

        if line == "quit":
            print("[Info]: Thanks for your use, Bye.")
            break

        if not searcher.isip(line):
            print("[Error]: Invalid ip address.")
            continue

        try:
            sTime = time.time() * 1000
            if algorithm == "binary":
                data = searcher.binarySearch(line)
            elif algorithm == "memory":
                data = searcher.memorySearch(line)
            else:
                data = searcher.btreeSearch(line)
            eTime = time.time() * 1000
            print("%s|%s in %5f millseconds" % (data["city_id"], data["region"].decode('utf-8'), eTime - sTime))
            result = data["region"].decode('utf-8')
            resultARR = result.split("|")
            returnARR1 = ["Country", "Province", "city", "isp"]
            returnARR2 = [resultARR[0], resultARR[2], resultARR[3], resultARR[4]]
            returnDICT = dict(zip(returnARR1, returnARR2))
            print(returnDICT)
            return returnDICT

        except Exception as e:
            print("[Error]: %s" % e)

    searcher.close()


if __name__ == "__main__":
    app.run(
        host="192.168.123.33",
        port=int("10746")
    )
